package org.springframework.samples.travel.infrastructure.security;

import java.util.HashSet;

import javax.inject.Inject;

import org.springframework.samples.travel.domain.model.user.UserRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("mongoUserDetails")
public class MongoUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;
    public static int numberOfFailedConnections = 0;
    public static int numberOfSuccessfulConnections = 0;

    @Inject
    public MongoUserDetailsService(UserRepository userRepository) {
	super();
	this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
	// UserDetails userDetails = userRepository.findByUsername(username);
	org.springframework.samples.travel.domain.model.user.User user = userRepository.findByUsername(username);
	HashSet<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();

	if (user == null) {
	    System.out.println("null user");
	    numberOfFailedConnections++;
	    throw new UsernameNotFoundException("invalid username");
	}

	for (int i = 0; i < user.getRoles().size(); i++) {
	    authorities.add(new SimpleGrantedAuthority(user.getRoles().get(i)));
	}
	System.out.println("\n \n" + user.getUsername() + "\n\n" + user.getPassword() + "\n\n");
	SecurityUser userDetails = new SecurityUser(user.getUsername(), user.getPassword(), true, true, true, true,
		authorities);
	userDetails.setUser(user);
	if (userDetails.getPassword() == null || userDetails.getUser() == null)
	    numberOfFailedConnections++;
	else
	    numberOfSuccessfulConnections++;

	System.out.println("\n\n" + userDetails + "\n\n");
	return userDetails;
    }
}
